/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/closest-binary-search-tree-value
   @Language: C++
   @Datetime: 19-05-07 11:01
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
	/**
	 * @param root: the given BST
	 * @param target: the given target
	 * @return: the value in the BST that is closest to the target
	 */
	int closestValue(TreeNode * root, double target) {
		// write your code here
		int val=root->val;
		for(TreeNode *p=root; p;){
			if(abs(p->val-target)<abs(val-target)) val=p->val;
			if(p->val>target) p=p->left;
			else p=p->right;
		}
		return val;
	}
};
